import os
import json
import re

def parse_word_line(line):
    """解析单词行，返回单词信息字典"""
    # 分割单词和释义
    parts = line.strip().split('\t')
    if len(parts) != 2:
        return None
        
    word, definitions = parts
    word = word.strip()
    
    # 解析词性和释义
    translations = []
    # 使用正则表达式匹配词性和释义
    # 例如: "n. 小船；轮船 v. 划船" -> [("n", "小船；轮船"), ("v", "划船")]
    pos_meanings = re.findall(r'([a-z]+\.)\s*([^a-z\.]+?)(?=[a-z]+\.|$)', definitions)
    
    for pos, meaning in pos_meanings:
        translations.append({
            "translation": meaning.strip('； '),
            "type": pos.strip('. ')
        })
    
    # 如果没有找到词性，将整个释义作为一个翻译
    if not translations:
        translations.append({
            "translation": definitions.strip(),
            "type": ""
        })
    
    return {
        "word": word,
        "translations": translations,
        "phrases": []  # 初始化为空列表，后续可以添加短语
    }

def convert_txt_to_json(txt_path, json_path):
    """将txt格式的词库转换为json格式"""
    word_bank = []
    
    try:
        with open(txt_path, 'r', encoding='utf-8') as f:
            for line in f:
                word_info = parse_word_line(line)
                if word_info:
                    word_bank.append(word_info)
        
        # 确保目标目录存在
        os.makedirs(os.path.dirname(json_path), exist_ok=True)
        
        # 写入json文件
        with open(json_path, 'w', encoding='utf-8') as f:
            json.dump(word_bank, f, ensure_ascii=False, indent=2)
            
        return True, f"Successfully converted {len(word_bank)} words"
    except Exception as e:
        return False, f"Error converting file: {str(e)}"

def main():
    # 项目根目录
    project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    word_banks_dir = os.path.join(project_root, 'data', 'word_banks')
    
    # 创建json目录
    json_dir = os.path.join(word_banks_dir, 'json')
    os.makedirs(json_dir, exist_ok=True)
    
    # 转换所有txt文件
    txt_files = [f for f in os.listdir(word_banks_dir) if f.endswith('.txt')]
    
    for txt_file in txt_files:
        txt_path = os.path.join(word_banks_dir, txt_file)
        json_file = txt_file.replace('.txt', '.json')
        json_path = os.path.join(json_dir, json_file)
        
        print(f"Converting {txt_file}...")
        success, message = convert_txt_to_json(txt_path, json_path)
        print(message)

if __name__ == "__main__":
    main() 